from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.db import connection
from django.http import JsonResponse, HttpResponse, QueryDict
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
import json

from .models import ApiAdmin
from .models import ApiBlack
from .models import ApiBook
from .models import ApiUser
from .models import ApiAuthor
from .models import ApiBorrow
from .models import ApiPublisher
# 登录
@csrf_exempt
def login(request):
    login_status = ''
    global user_info
    if request.method == 'POST':
        json_result = json.loads(request.body)
        username = json_result.get('name')
        password = json_result.get('password')
        user_obj = ApiAdmin.objects.filter(admin_id = username)
        if not user_obj:
            return HttpResponse('None')
        if password == user_obj[0].admin_pwd:
            user_info = True
            return HttpResponse(json.dumps(json_result, ensure_ascii=False),content_type='application/json')
        else:
            return HttpResponse('Wrong')
    return

# 添加图书
@require_http_methods(["POST"])
def add_book(request):
    response = {}
    try:
        json_results = json.loads(request.body)
        book_id = json_results.get('id')
        book_name = json_results.get('book_name')
        book_type = json_results.get('book_type')
        author = json_results.get('author')
        translator = json_results.get('translator')
        publisher = json_results.get('publisher')
        publish_time = json_results.get('publish_time')
        price = json_results.get('price')
        storage = json_results.get('storage')
        book = ApiBook(id = book_id,book_name = book_name,book_type = book_type,author = author,
                                      translator = translator,publisher = publisher,publish_time= publish_time,
                                      price = price, storage = storage)
        book.save()
        response['msg'] = 'success'
    except  Exception as e:
        response['msg'] = str(e)
    return JsonResponse(response)

# 添加用户
@require_http_methods(["POST"])
def add_user(request):
    response = {}
    try:
        json_results = json.loads(request.body)
        id = json_results.get('user_id')
        user_name = json_results.get('user_name')
        user_type = json_results.get('user_type')
        sex = json_results.get('sex')
        credit = json_results.get('credit')
        days = json_results.get('max_days')
        nums = json_results.get('max_num')
        user = ApiUser(id=id, user_id=id, user_name=user_name, user_type=user_type, sex=sex,
                                                  credit=credit, max_days=days, max_num=nums)
        user.save()
        response['msg'] = 'success'
    except  Exception as e:
        response['msg'] = str(e)
    return JsonResponse(response)


# 添加借阅
@require_http_methods(["POST"])
def add_rent(request):
    response = {}
    try:
        json_results = json.loads(request.body)
        print(json_results)
        user_id = json_results.get('newId')
        user_name = json_results.get('newName')
        book_id = json_results.get('newBookId')
        book_name = json_results.get('newBookName')
        borrow_date = timezone.now()
        rent = ApiBorrow(user_id = user_id, user_name=user_name, book_id=book_id, book_name=book_name,
                                                 borrow_date=borrow_date, if_back=0)
        rent.save()
        book = ApiBook.objects.get(id=book_id)
        book.storage -= 1
        book.save()
        response['msg'] = 'success'
    except  Exception as e:
        response['msg'] = str(e)
    return JsonResponse(response)

# 删除图书
@require_http_methods(["DELETE"])
def del_book(request):
    response = {}
    path = request.get_full_path()
    length = len(path)
    path = path[16:length]
    num = ''
    for i in path:
        if i != '&':
            num += i
        else:
            sql = "delete from api_book where id = " + num
            book = ApiBook.objects.filter(id = num)
            if(book):
                with connection.cursor() as cursor:
                    cursor.execute(sql)
                    num = ""
                    response['msg'] = 'success'
            else:
                response['msg'] = 'error'
    return JsonResponse(response)

# 删除用户
@require_http_methods(["DELETE"])
def del_user(request):
    response = {}
    path = request.get_full_path()
    length = len(path)
    path = path[16:length]
    num = ''
    for i in path:
        if i != '&':
            num += i
        else:
            sql = "delete from api_user where id = " + num
            user = ApiUser.objects.filter(id = num)
            if(user):
                with connection.cursor() as cursor:
                    cursor.execute(sql)
                    num = ""
                    response['msg'] = 'success'
            else:
                response['msg'] = 'error'
    return JsonResponse(response)


# 删除借阅
@require_http_methods(["DELETE"])
def del_rent(request):
    response = {}
    path = request.get_full_path()
    length = len(path)
    path = path[16:length]
    num = ''
    for i in path:
        if i != '&':
            num += i
        else:
            sql = "delete from api_borrow where id = " + num
            user = ApiBorrow.objects.filter(id = num)
            if(user):
                with connection.cursor() as cursor:
                    cursor.execute(sql)
                    num = ""
                    response['msg'] = 'success'
            else:
                response['msg'] = 'error'
    return JsonResponse(response)


# 展示图书
@require_http_methods(["GET"])
def show_books(request):
    response = {}
    try:
        books = ApiBook.objects.filter()
        authors = ApiAuthor.objects.filter()
        publishers = ApiPublisher.objects.filter()
        response['books'] = json.loads(serializers.serialize("json", books))
        response['authors'] = json.loads(serializers.serialize("json", authors))
        response['publishers'] = json.loads(serializers.serialize("json", publishers))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)


# 展示用户
@require_http_methods(["GET"])
def show_users(request):
    response = {}
    try:
        users = ApiUser.objects.filter()
        response['users'] = json.loads(serializers.serialize("json", users))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)


# 展示借阅
@require_http_methods(["GET"])
def show_rent(request):
    response = {}
    try:
        rents = ApiBorrow.objects.filter()
        response['rents'] = json.loads(serializers.serialize("json", rents))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)


# 查询图书
@require_http_methods(["PUT"])
@csrf_exempt
def select_book(request):
    response = {}
    path = request.GET
    li = list(path.items())
    dict = {}
    books = []
    flag = False
    sql = "select * from api_book where "
    for i in li:
        dict[i[0]] = i[1]
    if (len(li) > 1):
        flag = True
    if flag:
        if (dict.get('book_name') != None):
            sql1 = "book_name='" + dict.get('book_name') + "' "
            sql += sql1 + 'and '
        if (dict.get('type') != None):
            sql2 = "book_type='" + dict.get('type') + "' "
            sql += sql2 + 'and '
        if (dict.get('author') != None):
            sql3 = "author='" + dict.get('author') + "' "
            sql += sql3 + 'and '
        if (dict.get('publisher') != None):
            sql4 = "publisher='" + dict.get('publisher') + "' "
            sql += sql4
    else:
        sql += li[0][0] + "='" + li[0][1] + "'"
    with connection.cursor() as cursor:
        cursor.execute(sql)
        rows = dictfetchall(cursor)
    response['books'] =rows
    return JsonResponse(response)


# 查询用户
@require_http_methods(["PUT"])
@csrf_exempt
def select_user(request):
    response = {}
    path = request.GET
    li = list(path.items())
    dict = {}
    users = []
    flag = False
    sql = "select * from api_user where "
    for i in li:
        dict[i[0]] = i[1]
    if (len(li) > 1):
        flag = True
    if flag:
        if (dict.get('user_name') != None):
            sql1 = "user_name='" + dict.get('user_name') + "' "
            sql += sql1 + 'and '
        if (dict.get('user_type') != None):
            sql2 = "user_type='" + dict.get('user_type') + "' "
            sql += sql2
    else:
        sql += li[0][0] + "='" + li[0][1] + "'"
    with connection.cursor() as cursor:
        cursor.execute(sql)
        rows = dictfetchall(cursor)
    response['users'] =rows
    return JsonResponse(response)


# 查询借阅
@require_http_methods(["PUT"])
@csrf_exempt
def select_rent(request):
    response = {}
    path = request.GET
    li = list(path.items())
    dict = {}
    flag = False
    sql = "select * from api_borrow where "
    for i in li:
        dict[i[0]] = i[1]
    if (len(li) > 1):
        flag = True
    if flag:
        if (dict.get('id') != None):
            sql1 = "id='" + dict.get('id') + "' "
            sql += sql1 + 'and '
        if (dict.get('user_name') != None):
            sql2 = "user_name='" + dict.get('user_name') + "' "
            sql += sql2 + 'and '
        if (dict.get('book_name') != None):
            sql3 = "book_name='" + dict.get('book_name') + "' "
            sql += sql3 + 'and '
        if (dict.get('status') != None):
            sql4 = "if_back='" + dict.get('status') + "' "
            sql += sql4
    else:
        sql += li[0][0] + "='" + li[0][1] + "'"
        print(sql)
    with connection.cursor() as cursor:
        cursor.execute(sql)
        rows = dictfetchall(cursor)
    response['rents'] =rows
    return JsonResponse(response)

# 编辑图书
@require_http_methods(["POST"])
def edit_book(request):
    response = {}
    try:
        json_results = json.loads(request.body)
        book_id = json_results.get('id')
        book_name = json_results.get('book_name')
        book_type = json_results.get('book_type')
        author = json_results.get('author')
        translator = json_results.get('translator')
        publisher = json_results.get('publisher')
        publish_time = json_results.get('publish_time')
        price = json_results.get('price')
        storage = json_results.get('storage')
        ApiBook.objects.filter(id = book_id).update(book_name = book_name, book_type = book_type, author = author,
                                                           translator = translator, publisher = publisher, publish_time = publish_time,
                                                           price = price, storage = storage)
        response['msg'] = 'success'
    except  Exception as e:
        response['msg'] = str(e)
    return JsonResponse(response)

# 编辑用户
@require_http_methods(["POST"])
def edit_user(request):
    response = {}
    try:
        json_results = json.loads(request.body)
        user_id = json_results.get('id')
        user_name = json_results.get('user_name')
        user_type = json_results.get('user_type')
        sex = json_results.get('sex')
        credit = json_results.get('credit')
        days = json_results.get('max_days')
        nums = json_results.get('max_num')
        ApiUser.objects.filter(id = user_id).update(user_name = user_name, user_type = user_type, sex = sex,
                                                           credit = credit, max_days = days, max_num = nums)
        response['msg'] = 'success'
    except  Exception as e:
        response['msg'] = str(e)
    return JsonResponse(response)


# 编辑借阅
@require_http_methods(["POST"])
def edit_rent(request):
    response = {}
    try:
        json_results = json.loads(request.body)
        rent_id = json_results.get('id')
        user_id = json_results.get('user_id')
        user_name = json_results.get('user_name')
        book_id = json_results.get('book_id')
        book_name = json_results.get('book_name')
        status = json_results.get('if_back')
        borrow_date = json_results.get('borrow_date')
        ApiBorrow.objects.filter(id = rent_id).update(user_name = user_name, user_id = user_id, book_id = book_id,
                                                    book_name = book_name, if_back = status, borrow_date=borrow_date)
        response['msg'] = 'success'
    except  Exception as e:
        response['msg'] = str(e)
    return JsonResponse(response)

# 纯sql返回dict数据
def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]